/**
 * 2024/01/01 - 2024/12/31
 **/
package com.snail.camunda.engin.identity.holder;

import com.snail.camunda.engin.errorcode.CamundaErrorCode;
import com.snail.camunda.engin.identity.dto.TenantInsertDTO;
import com.snail.camunda.engin.identity.dto.TenantModifyDTO;
import com.snail.start.utils.id.ObjectId;
import com.snail.starter.commons.exception.BizException;
import com.snail.starter.commons.page.PageQO;
import com.snail.starter.commons.page.PageVO;
import org.camunda.bpm.engine.IdentityService;
import org.camunda.bpm.engine.identity.Tenant;
import org.camunda.bpm.engine.identity.TenantQuery;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: (zg)
 * @Date: 2024/12/16 15:13
 * @Version: 1.0.0
 */
@Component
public class TenantHolder {

    @Resource
    IdentityService identityService;

    public String add(TenantInsertDTO dto) {
        Tenant tenant = identityService.newTenant(String.valueOf(ObjectId.nextLongId()));
        tenant.setName(dto.getName());
        identityService.saveTenant(tenant);
        return tenant.getId();
    }

    public boolean modify(String id, TenantModifyDTO dto) {
        Tenant tenant = queryById(id);
        if (null == tenant) {
            throw BizException.of(CamundaErrorCode.USER_NOT_EXISTS);
        }
        if (null == dto) {
            return true;
        }
        if(null != dto.getName()){
            tenant.setName(dto.getName());
        }
        identityService.saveTenant(tenant);
        return true;
    }

    public Tenant queryById(String id) {
        TenantQuery tenantQuery = createTenantQuery(null);
        tenantQuery.tenantId(id);
        return tenantQuery.singleResult();
    }

    public boolean deleteById(String id) {
        identityService.deleteTenant(id);
        return true;
    }

    public List<Tenant> list(String name) {
        TenantQuery tenantQuery = createTenantQuery(name);
        return tenantQuery.list();
    }

    public PageVO<Tenant> page(PageQO<String> page) {
        TenantQuery tenantQuery = createTenantQuery(page.getQuery());
        long count = tenantQuery.count();
        if (0 == count) {
            return PageVO.of(page.getPageNum() - 1, page.getPageSize(), 0L, new ArrayList<>());
        }
        return PageVO.of(page.getPageNum(), page.getPageSize(), count, tenantQuery.listPage(page.getPageNum(), page.getPageSize()));
    }

    public TenantQuery createTenantQuery(String name) {
        TenantQuery tenantQuery = identityService.createTenantQuery();
        if (null != name) {
            tenantQuery.tenantNameLike("%" + name + "%");
        }
        return tenantQuery;
    }

}